#!/usr/bin/env python   
#-*- coding: utf-8 -*-
import sys  
import string  
import codecs  
import os  
import shutil  
from time import sleep


  
def gbkToUtf8(path):  
    files = os.listdir(path + "/gbk/")  
    for filename in files:  
        fileGBK = path + '/gbk/' + filename  
        fileUTF = path + '/utf/' + filename  
        #print fileGBK   
        if os.path.isdir(fileGBK):  
            gbkToUtf8(fileGBK)  
            continue  
  
        print 'Encode Converting (GBK to UTF-8) : ', fileGBK  
  
        try:  
            tokens = string.splitfields(filename, '.')  
            print 'tokens :',tokens  
            print 'tokenslength:',len(tokens)  

            if len(tokens) != 2 or tokens[1] != 'htm':  
                #print tokens[1]   
                shutil.copy(fileGBK, fileUTF)  
                print 'shutil.copy:',len(tokens)  

            else:  
                print 'becopyutf8:',len(tokens)  
                str = open(fileGBK).read().decode("gbk")  
                print 'becopyutf1:',len(tokens)  
                str = str.encode("UTF-8")  
                print 'becopyutf2:',len(tokens)  
                utfFile = open(fileUTF, 'w')  
                print 'becopyutf3:',len(tokens)  
                utfFile.write(str)  
                print 'becopyutf4:',len(tokens)  
                utfFile.close()  
                print 'becopyutf5:',len(tokens)  
        except:  
            print "error"  
            
            
          
if __name__ == "__main__":  
    a=100
    c=0
    while a>1:
        gbkToUtf8("E:/wugang/")
        files = os.listdir("E:/wugang/stop/")
        for filename in files:
            print 'exitNOW:'  
            a=0
        if a>1:
            c=c+1
            print '循环:',c,'次'  
            sleep(5)  
